import {
	login,
	logout,
	getUserInfo
} from '@/api/login'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/app'

const state = {
	to_ken: getToken() || '', // 刷新页面就会掉，所有先从本地拿
	user: null, // 用户信息
	avatar: '/assets/tx.jpg', // 用户头像 默认
	roles: [], // 保存当前用户的角色
	curRoleFlag: '', // 当前用户角色
	permissions: [] // //保存当前用户的权限
}
const getters = {
	user: state => state.user,
	roles: state => state.roles,
	curRoleFlag: state => state.curRoleFlag,
	permissions: state => state.permissions,
	avatar: state => state.avatar
}
const mutations = {
	SET_TOKE(state, value) {
		state.to_ken = value;
	},
	SET_USER(state, value) {
		state.user = value
	},
	SET_ROlES(state, value) {
		state.roles = value
	},
	SET_ROLE_FLAG(state, value) {
		state.curRoleFlag = value
	},
	SET_USER_AVATAR(state, value) {
		state.avatar = value
	},
	SET_PERMISSIONS(state, value) {
		state.permissions = value
	}
}

const actions = {
	// 登录
	Login(context, userInfo) { // {commit} //代表使用  mutations 里面的方法 也可以这样 写 context代表store里的所有方法 如 var commit=context.commit
		return new Promise((resolve, reject) => {
			login(userInfo).then(res => {
				if (res.data.code === 0) {
					context.commit('SET_TOKE', res.data.data); // 存到 store
					setToken(res.data.data); // 存到本地
				}
				resolve(res)
			}).catch(error => {
				reject(error)
			})
		})
	},
	// getRoles
	GetUserInfo({ commit }) {
		return new Promise((resolve, reject) => {
			// 向后端请求路由数据
			getUserInfo().then(res => {
				if (res.code === 0) {
					commit('SET_USER', res.data)// 用户信息
					commit('SET_USER_AVATAR', res.data.avatar)
					commit('SET_ROlES', res.data.roles)
					if (res.data.roles && res.data.roles.length > 0) {
						console.log('获取用户信息')
						let curRoleObj = {};
						res.data.roles.forEach((item) => {
							if ((item.code === 'leader_a' || item.code === 'leader_b' || item.code === 'leader_c')) {	// 领导
								curRoleObj['leader'] = true
							} else {
								curRoleObj[item.code] = true
							}
						});
						commit('SET_ROLE_FLAG', curRoleObj)
					}
					commit('SET_PERMISSIONS', res.data.permissions)
					resolve(res)
				} else {
					reject(res)
				}
			})
		})
	},
	// 退出系统
	LogOut({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			logout(state.token).then(() => {
				commit('SET_TOKE', '')
				commit('SET_USER', null)
				removeToken()
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},
}
export default {
	namespaced: true,
	actions,
	state,
	mutations,
	getters
};
